<template>
  <div class="app-container">
    <div class="filter-container">
      <el-form>
        <el-form-item>
          <el-button type="danger" icon="plus" v-if="hasPerm('user:add')" @click="showCreate">添加
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-row :gutter="20" style="margin-bottom: 20px;">
      <el-col :span="5">
        <p style="color: #989A9A;">用户名</p>
        <el-input placeholder="输入用户名" v-model="searchParam.userName" @keyup.enter.native="getList('search')"></el-input>
      </el-col>

      <el-col :span="4">
        <p>&nbsp;</p>
        <el-button type="danger" @click="getList('search')">搜索</el-button>
      </el-col>

    </el-row>
    <el-table :data="list" v-loading.body="listLoading" element-loading-text="拼命加载中" border fit
              highlight-current-row>
      <el-table-column align="center" label="序号" width="80">
        <template slot-scope="scope">
          <span v-text="getIndex(scope.$index)"> </span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="用户名" prop="userName" min-width="30%"></el-table-column>
      <el-table-column align="center" label="角色" min-width="20%">
        <template slot-scope="scope">
          <el-tag type="primary" v-text="scope.row.roleName"></el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="管理" min-width="30%" v-if="hasPerm('user:edit')">
        <template slot-scope="scope">
          <el-button type="danger" icon="edit" @click="resetPasswd(scope.$index)" v-if="scope.row.id !==9">重置密码</el-button>
          <el-button type="danger" icon="edit" @click="showUpdate(scope.$index)" v-if="scope.row.id !== 9">修改</el-button>
          <el-button type="danger" icon="delete" v-if="hasPerm('user:delete') && scope.row.id !== userId && scope.row.id !== 9"
                     @click="removeUser(scope.$index)">删除
          </el-button>
          <strong v-if="scope.row.id === 9"><h1>抱歉，有权限是真的可以为所欲为！</h1></strong>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @current-change="handleCurrentChange"
      :current-page="listQuery.pageNum"
      :page-size="listQuery.pageSize"
      :total="totalCount"
      layout=" prev, pager, next">
    </el-pagination>
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form class="small-space" :model="tempUser" label-position="left" label-width="80px"
               style='width: 300px; margin-left:50px;' v-if="dialogStatus==='create'">
       <el-form-item label="用户名">
          <el-input type="text" v-model="tempUser.userName">
          </el-input>
        </el-form-item>
        
        <el-form-item label="角色">
          <el-select v-model="tempUser.roleId">
              <el-option 
                  v-for="item in state"
                  :key="item.id"
                  :label="item.roleName"
                  :value="item.id">
              </el-option>
          </el-select>
        
        </el-form-item>
        
      </el-form>
      <el-form v-else class="small-space" :model="tempUser" label-position="left" label-width="80px"
               style='width: 300px; margin-left:50px;'>
        <el-form-item label="角色">
          <el-select v-model="tempUser.roleId">
              <el-option 
                  v-for="item in state"
                  :key="item.id"
                  :label="item.roleName"
                  :value="item.id">
              </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button v-if="dialogStatus=='create'" type="danger" @click="createUser">创 建</el-button>
        <el-button v-if="dialogStatus=='update'" type="danger" @click="updateUser">修 改</el-button>
      </div>
    </el-dialog>

  </div>
</template>
<script>
  import {mapGetters} from 'vuex'

  export default {
    data() {
      return {
        totalCount: 0, //分页组件--数据总条数
        list: [],//表格的数据
        listLoading: false,//数据加载等待动画
        listQuery: {
          pageNum: 1,//页码
          pageSize: 15,//每页条数
        },
        searchParam: {
          userName: ''
        },
        roles: [],//角色列表
        dialogStatus: 'create',
        dialogFormVisible: false,
        textMap: {
          update: '编辑',
          create: '新建用户'
        },
        tempUser: {
          userName: '',
          password: '',
          nickname: '',
          roleId: '',
          userId: ''
        },
        roleListOption: [],
        loading: false,
        state: [],
        userId: this.$store.getters.userId
      }
    },
    created() {
      this.getList();
      if (this.hasPerm('user:add') || this.hasPerm('user:edit')) {
        this.getAllRoles()
      }
    },
    methods: {
      async getAllRoles() {
        const res = await this.$api.sysrole.list(1, 1, false)
        this.state = res.data
        this.roles = this.state.map(item => {
            return { value: item.id, label: item.roleName }
        })
      },
      transformRoleList(query) {
        if (query !== '') {
          this.loading = true;
          setTimeout(() => {
              this.loading = false;
              this.roleListOption = this.roles.filter(item => {
                  return item.label.toLowerCase()
                    .indexOf(query.toLowerCase()) > -1
              });
          }, 200);
        } else {
          this.roleListOption = []
        }
      },
      async getList(search) {
        //查询列表
        this.listLoading = true;
        const res = (search && search === 'search') ? 
          await this.$api.sysuser.search(this.listQuery.pageSize, this.listQuery.pageNum, this.searchParam)
          : await this.$api.sysuser.list(this.listQuery.pageSize, this.listQuery.pageNum, true)
        this.list = res.data.data
        this.totalCount = res.data.total
        this.listLoading = false
      },
      handleSizeChange(val) {
        //改变每页数量
        this.listQuery.pageSize = val
        this.handleFilter()
      },
      handleCurrentChange(val) {
        //改变页码
        this.listQuery.pageNum = val
        this.getList()
      },
      handleFilter() {
        //查询事件
        this.listQuery.pageNum = 1
        this.getList()
      },
      getIndex($index) {
        //表格序号
        return (this.listQuery.pageNum - 1) * this.listQuery.pageSize + $index + 1
      },
      showUpdate($index) {
        this.tempUser = JSON.parse(JSON.stringify(this.list[$index]))
        this.dialogStatus = "update"
        this.dialogFormVisible = true
      },
      showCreate() {
        //显示新增对话框
        this.selectedRole = {}
        this.tempUser.userName = ""
        this.tempUser.password = ""
        this.tempUser.nickname = ""
        this.tempUser.roleId = ""
        this.tempUser.userId = ""
        this.tempUser.roleName = ''
        this.dialogStatus = "create"
        this.dialogFormVisible = true
      },
      async createUser() {
        await this.$api.sysuser.add(this.tempUser)
        this.getList()
        this.dialogFormVisible = false
      },
      async updateUser() {
        await this.$api.sysuser.edit(this.tempUser)
        this.getList()
        this.dialogFormVisible = false
      },
      resetPasswd($index) {
        let _vue = this;
        this.$confirm('确认重置密码?', '提示', {
          confirmButtonText: '确认',
          showCancelButton: false,
          type: 'warning'
        }).then(async () => {
          let user = _vue.list[$index]
          _vue.$api.sysuser.resetPasswd(user.id)
          _vue.$message.success('重置成功')
          _vue.getList()
        })
      },
      removeUser($index) {
        let _vue = this;
        this.$confirm('确定删除此用户?', '提示', {
          confirmButtonText: '确定',
          showCancelButton: false,
          type: 'warning'
        }).then(async () => {
          let user = _vue.list[$index];
          user.deleteStatus = '2';
          _vue.$api.sysuser.delete(user.id)
          _vue.$message.success('删除成功')
          _vue.getList()
        })
      },
    }
  }
</script>
